﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Diagnostics;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Display;
using Autodesk.AutoCAD.Interop;
using Autodesk.AutoCAD.Interop.Common;

using DWGdirect.DatabaseServices;
using DWGdirect.DatabaseServices.Filters;
using DWGdirect.Geometry;
using DWGdirect.Runtime;
using PlanningGIS.Util.Win32;
using PlanningGIS.Util.Log;
namespace PlanningGIS.DataConvert.model
{
    /// <summary>
    /// 导出Dwg
    /// </summary>
    public class DwgExportUtility2
    {
        private IAcadDocument mCadDoc;
        private Database mDb;
        private ComObject mCadDoc2;

        /// <summary>
        /// check if autocad is installed
        /// </summary>
        /// <returns></returns>
        public static bool CheckCadInstall(out string strExePath)
        {
            strExePath = "";
            try
            {
                string strKey = "SOFTWARE\\Autodesk\\AutoCAD";
                Microsoft.Win32.RegistryKey pRegKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(strKey, false);
                if (pRegKey == null) return false;
                string[] strSubKeys = pRegKey.GetSubKeyNames();
                if (strSubKeys.Length == 0) return false;
                for (int i = 0; i < strSubKeys.Length; i++)
                {
                    if (strSubKeys[i].Trim().ToUpper().StartsWith("R"))
                    {
                        string strVersion = strSubKeys[i].Trim().ToUpper().Remove(0, 1);
                        double version;
                        if (double.TryParse(strVersion, out version))
                        {
                            if (version >= 17)
                            {
                                RegistryKey pSubKey = pRegKey.OpenSubKey(strSubKeys[i]);
                                if (pSubKey.SubKeyCount == 0) break;
                                RegistryKey pSubSubKey = pSubKey.OpenSubKey(pSubKey.GetSubKeyNames()[0]);
                                strExePath = pSubSubKey.GetValue("Location").ToString() + "\\acad.exe";
                                 if (System.IO.File.Exists(strExePath )) return true;
                            }
                        }
                    }
                }
            }
            catch (System.Exception)
            {
                return false;
            }
            return true;
        }

        public IAcadDocument AcadDocument
        {
            set
            {
                mCadDoc = value;
            }
            get
            {
                return mCadDoc;
            }
        }
        public Database Db
        {
            set
            {
                mDb = value;
            }
            get
            {
                return mDb;
            }

        }
        public ComObject AcadDocument2
        {
            set
            {
                mCadDoc2 = value;
            }
            get
            {
                return mCadDoc2;
            }
        }

        /// <summary>
        /// ArcEngiene Polyline to AutoCAD Polyline
        /// </summary>
        /// <param name="pPolyline"></param>
        /// <returns></returns>
        public List<IAcadLWPolyline> Esri2CadPolyline(IPolyline pPolyline, string strLayerName, AcadAcCmColor pCadColor, string strStyle)
        {
            List<IAcadLWPolyline> pAcadPolylineList = new List<IAcadLWPolyline>();
            try
            {
                IGeometryCollection pGeometryCollection = pPolyline as IGeometryCollection;
                int count = pGeometryCollection.GeometryCount;
                for (int i = 0; i < count; i++)
                {
                    IPointCollection pPts = pGeometryCollection.get_Geometry(i) as IPointCollection;
                    int ptCount = pPts.PointCount;
                    double[] dblVertex = new double[ptCount * 2];
                    for (int j = 0; j < ptCount; j++)
                    {
                        dblVertex[j * 2] = pPts.get_Point(j).X;
                        dblVertex[j * 2 + 1] = pPts.get_Point(j).Y;

                    }
                    IAcadLWPolyline pCadPolyline = mCadDoc.ModelSpace.AddLightWeightPolyline(dblVertex);
                    pCadPolyline.Layer = strLayerName;
                    if (strStyle != "")
                    {
                        //try
                        //{
                        //    pCadPolyline.Linetype = strStyle;
                        //}
                        //catch (System.Exception)
                        //{
                        mCadDoc.Linetypes.Add(strStyle);
                        pCadPolyline.Linetype = strStyle;
                        //}
                    }
                    if (pCadColor != null) pCadPolyline.TrueColor = pCadColor;
                    pAcadPolylineList.Add(pCadPolyline);

                }
            }
            catch (System.Exception)
            {
            }
            return pAcadPolylineList;
        }

        public List<DWGdirect.DatabaseServices.Polyline> Esri2CadPolyline(Transaction pTran,BlockTableRecord pBtr, IPolyline pPolyline, string strLayerName, DWGdirect.Colors.Color pCadColor, string strStyle)
        {
            List<DWGdirect.DatabaseServices.Polyline> pAcadPolylineList = new List<DWGdirect.DatabaseServices.Polyline>();
            try
            {
                IGeometryCollection pGeometryCollection = pPolyline as IGeometryCollection;
                int count = pGeometryCollection.GeometryCount;
                for (int i = 0; i < count; i++)
                {
                    DWGdirect.DatabaseServices.Polyline pCadPolyline = new DWGdirect.DatabaseServices.Polyline();
                   
                    IPointCollection pPts = pGeometryCollection.get_Geometry(i) as IPointCollection;
                    int ptCount = pPts.PointCount;
                  
                    for (int j = 0; j < ptCount; j++)
                    {                        
                        pCadPolyline.AddVertexAt(pCadPolyline.NumberOfVertices,new Point2d(pPts.get_Point(j).X,pPts.get_Point(j).Y),0,0,0);
                    }                                                          
                    if (strStyle != "")
                    {                       
                        mCadDoc.Linetypes.Add(strStyle);
                        pCadPolyline.Linetype = strStyle;                       
                    }
               
                    
                    pAcadPolylineList.Add(pCadPolyline);
                    pBtr.AppendEntity(pCadPolyline);
                    pTran.AddNewlyCreatedDBObject(pCadPolyline,true);
                    pCadPolyline.Layer = strLayerName;
                    pCadPolyline.Color = pCadColor;

                }
            }
            catch (System.Exception)
            {

            }
            return pAcadPolylineList;
        }

        public List<ComObject> Esri2CadPolyline2(IPolyline pPolyline, string strLayerName, ComObject pCadColor)
        {
            List<ComObject> pAcadPolylineList = new List<ComObject>();
            try
            {
                IGeometryCollection pGeometryCollection = pPolyline as IGeometryCollection;
                int count = pGeometryCollection.GeometryCount;
                for (int i = 0; i < count; i++)
                {
                    IPointCollection pPts = pGeometryCollection.get_Geometry(i) as IPointCollection;
                    int ptCount = pPts.PointCount;
                    double[] dblVertex = new double[ptCount * 2];
                    for (int j = 0; j < ptCount; j++)
                    {
                        dblVertex[j * 2] = pPts.get_Point(j).X;
                        dblVertex[j * 2 + 1] = pPts.get_Point(j).Y;
                    }
                    //IAcadLWPolyline pCadPolyline = mCadDoc.ModelSpace.AddLightWeightPolyline(dblVertex);
                    //pCadPolyline.Layer = strLayerName;
                    //if (pCadColor != null) pCadPolyline.TrueColor = pCadColor;
                    //pAcadPolylineList.Add(pCadPolyline);

                    ComObject pModelSpace = ComObject.CreateInstance(mCadDoc2["ModelSpace"]);
                    ComObject pCadPolyline = ComObject.CreateInstance(pModelSpace.InvokeMethod("AddLightWeightPolyline", dblVertex));
                    pCadPolyline["Layer"] = strLayerName;
                    if (pCadColor != null)
                    {
                        pCadPolyline["TrueColor"] = pCadColor;
                    }
                    pAcadPolylineList.Add(pCadPolyline);
                }
            }
            catch (System.Exception)
            {
            }
            return pAcadPolylineList;
        }


        public IAcadRegion Esri2CadRegion(IPolygon pPolygon, string strLayerName, AcadAcCmColor pCadColor)
        {
            AcadRegion pAcadRegion = null;
            AcadRegion pAcadRegion2 = null;        
            AcadHatch pHatch = null;
            try
            {
                pHatch = mCadDoc.ModelSpace.AddHatch((int)AcPatternType.acHatchPatternTypePreDefined, "SOLID", true, AcHatchObjectType.acHatchObject);
                pHatch.Layer = strLayerName;
                IGeometryBag pOutRings = ((IPolygon4)pPolygon).ExteriorRingBag;
                IEnumGeometry pOutRingsEnum = pOutRings as IEnumGeometry;
                pOutRingsEnum.Reset();
                IRing currentOutRing = pOutRingsEnum.Next() as IRing;
                while (currentOutRing != null)
                {
                    pAcadRegion2 = EsriRing2CadRegion(currentOutRing, strLayerName, pCadColor);
                    pHatch.AppendOuterLoop(new AcadRegion[] { pAcadRegion2 });
                    IGeometryBag inRings = ((IPolygon4)pPolygon).get_InteriorRingBag(currentOutRing);
                    IEnumGeometry pInRingsEnum = inRings as IEnumGeometry;
                    pInRingsEnum.Reset();
                    IRing currentInRing = pInRingsEnum.Next() as IRing;
                    while (currentInRing != null)
                    {
                        AcadRegion pCadRegionIn = EsriRing2CadRegion(currentInRing, strLayerName, pCadColor);
                        pHatch.AppendInnerLoop(new AcadRegion[] { pCadRegionIn });
                        pAcadRegion2.Boolean(AcBooleanType.acSubtraction, pCadRegionIn as AcadRegion);
                        currentInRing = pInRingsEnum.Next() as IRing;
                    }
                    if (pAcadRegion == null)
                    {
                        pAcadRegion = pAcadRegion2;
                    }
                    else
                    {
                        pAcadRegion.Boolean(AcBooleanType.acUnion, pAcadRegion2 as AcadRegion);
                        Marshal.ReleaseComObject(pAcadRegion2);
                        pAcadRegion2 = null;
                    }
                    currentOutRing = pOutRingsEnum.Next() as IRing;
                }
                if (pAcadRegion != null && pCadColor != null)
                {
                    pHatch.TrueColor = pCadColor;
                    pHatch.Layer = strLayerName;
                    pHatch.Evaluate();
                    pAcadRegion.Layer = strLayerName;
                    
                }
            }
            catch (System.Exception)
            {
            }
            finally
            {
                Marshal.ReleaseComObject(pHatch);
                pHatch = null;
            }
            return pAcadRegion as IAcadRegion;
        }
        public List<Region> Esri2CadRegion(Transaction pTran, BlockTableRecord pBtr, IPolygon pPolygon, string strLayerName, DWGdirect.Colors.Color pCadColor)
        {
            List<Region> regions = new List<Region>();
            if (((IGeometryCollection)pPolygon).GeometryCount == 1)
            {
                Region regionOut = EsriRing2CadRegion(pTran, pBtr, pPolygon as IPointCollection, strLayerName, pCadColor);
                regions.Add(regionOut);
            }
            else
            {
                IGeometryBag pOutRings = ((IPolygon4)pPolygon).ExteriorRingBag;
                IEnumGeometry pOutRingsEnum = pOutRings as IEnumGeometry;
                pOutRingsEnum.Reset();
                IRing currentOutRing = pOutRingsEnum.Next() as IRing;
                while (currentOutRing != null)
                {
                    Region regionOut = EsriRing2CadRegion(pTran, pBtr, currentOutRing, strLayerName, pCadColor);
                    regions.Add(regionOut);

                    IGeometryBag inRings = ((IPolygon4)pPolygon).get_InteriorRingBag(currentOutRing);
                    IEnumGeometry pInRingsEnum = inRings as IEnumGeometry;
                    pInRingsEnum.Reset();
                    IRing currentInRing = pInRingsEnum.Next() as IRing;
                    while (currentInRing != null)
                    {
                        Region regionIn = EsriRing2CadRegion(pTran, pBtr, currentInRing, strLayerName, pCadColor);
                        regions.Add(regionIn);
                        currentInRing = pInRingsEnum.Next() as IRing;
                    }
                    currentOutRing = pOutRingsEnum.Next() as IRing;
                }
            }
              

            return regions;
        }
        //public Region Esri2CadRegion(Transaction pTran,BlockTableRecord pBtr, IPolygon pPolygon, string strLayerName, DWGdirect.Colors.Color pCadColor)
        //{
        //    Region pAcadRegion = null;
        //    Region pAcadRegion2 = null;         
        //    try
        //    {              
        //        IGeometryBag pOutRings = ((IPolygon4)pPolygon).ExteriorRingBag;
        //        IEnumGeometry pOutRingsEnum = pOutRings as IEnumGeometry;
        //        pOutRingsEnum.Reset();
        //        IRing currentOutRing = pOutRingsEnum.Next() as IRing;
        //        while (currentOutRing != null)
        //        {
        //            pAcadRegion2 = EsriRing2CadRegion(pTran,pBtr, currentOutRing, strLayerName, pCadColor);
        //            pAcadRegion2.SetDatabaseDefaults(pBtr.Database);
        //            IGeometryBag inRings = ((IPolygon4)pPolygon).get_InteriorRingBag(currentOutRing);
        //            IEnumGeometry pInRingsEnum = inRings as IEnumGeometry;
        //            pInRingsEnum.Reset();
        //            IRing currentInRing = pInRingsEnum.Next() as IRing;
        //            while (currentInRing != null)
        //            {
        //                Region pCadRegionIn = EsriRing2CadRegion(pTran, pBtr, currentInRing, strLayerName, pCadColor);
        //                pCadRegionIn.SetDatabaseDefaults(pBtr.Database);                      
        //                pAcadRegion2.BooleanOperation(BooleanOperationType.BoolSubtract, pCadRegionIn as Region);
        //                currentInRing = pInRingsEnum.Next() as IRing;                       
        //            }
        //            if (pAcadRegion == null)
        //            {
        //                pAcadRegion = pAcadRegion2;
        //            }
        //            else
        //            {
        //                pAcadRegion.BooleanOperation(BooleanOperationType.BoolUnite, pAcadRegion2 as Region);
        //                Marshal.ReleaseComObject(pAcadRegion2);
        //                pAcadRegion2 = null;
        //            }
        //            currentOutRing = pOutRingsEnum.Next() as IRing;
        //        }
        //        if (pAcadRegion != null && pCadColor != null)
        //        {               
        //            pAcadRegion.Layer = strLayerName;
        //        }
        //    }
        //    catch (System.Exception)
        //    {
        //    }
        //    finally
        //    {                
        //    }
        //    return pAcadRegion ;
        //}
        public ComObject Esri2CadRegion2(IPolygon pPolygon, string strLayerName, ComObject pCadColor)
        {
            ComObject pAcadRegion = null;
            ComObject pAcadRegion2 = null;
            ComObject pHatch = null;
            try
            {
                ComObject pModelSpace = ComObject.CreateInstance(mCadDoc2["ModelSpace"]);
                pHatch = ComObject.CreateInstance(pModelSpace.InvokeMethod("AddHatch", 1, "SOLID", true, 0));
                // pHatch = mCadDoc.ModelSpace.AddHatch((int)AcPatternType.acHatchPatternTypePreDefined, "SOLID", true, AcHatchObjectType.acHatchObject);
                IGeometryBag pOutRings = ((IPolygon4)pPolygon).ExteriorRingBag;
                IEnumGeometry pOutRingsEnum = pOutRings as IEnumGeometry;
                pOutRingsEnum.Reset();
                IRing currentOutRing = pOutRingsEnum.Next() as IRing;
                while (currentOutRing != null)
                {
                    pAcadRegion2 = EsriRing2CadRegion2(currentOutRing, strLayerName, pCadColor);
                    //pHatch.AppendOuterLoop(new AcadRegion[] { pAcadRegion2 });
                    pHatch.InvokeMethod("AppendOuterLoop", new ComObject[] { pAcadRegion2 });
                    IGeometryBag inRings = ((IPolygon4)pPolygon).get_InteriorRingBag(currentOutRing);
                    IEnumGeometry pInRingsEnum = inRings as IEnumGeometry;
                    pInRingsEnum.Reset();
                    IRing currentInRing = pInRingsEnum.Next() as IRing;
                    while (currentInRing != null)
                    {
                        ComObject pCadRegionIn = EsriRing2CadRegion2(currentInRing, strLayerName, pCadColor);
                        //pHatch.AppendInnerLoop(new AcadRegion[] { pCadRegionIn });
                        pHatch.InvokeMethod("AppendOuterLoop", new ComObject[] { pCadRegionIn });
                        // pAcadRegion2.Boolean(AcBooleanType.acSubtraction, pCadRegionIn as AcadRegion);
                        pAcadRegion2.InvokeMethod("Boolean", 2, pCadRegionIn);
                        currentInRing = pInRingsEnum.Next() as IRing;
                    }
                    if (pAcadRegion == null)
                    {
                        pAcadRegion = pAcadRegion2;
                    }
                    else
                    {
                        //pAcadRegion.Boolean(AcBooleanType.acUnion, pAcadRegion2 as AcadRegion);
                        pAcadRegion.InvokeMethod("Boolean", 0, pAcadRegion2);
                    }
                    currentOutRing = pOutRingsEnum.Next() as IRing;
                }
                if (pAcadRegion != null && pCadColor != null)
                {
                    //pHatch.TrueColor = pCadColor;
                    //pHatch.Layer = strLayerName;
                    //pHatch.Evaluate();
                    //pAcadRegion.Layer = strLayerName;
                    //Marshal.ReleaseComObject(pHatch);

                    pHatch["TrueColor"] = pCadColor;
                    pHatch["Layer"] = strLayerName;
                    pHatch.InvokeMethod("Evaluate");
                    pAcadRegion["Layer"] = strLayerName;
                }
            }
            catch (System.Exception)
            {
            }
            return pAcadRegion;
        }

        private ComObject EsriRing2CadRegion2(IRing pRing, string strLayerName, ComObject pCadColor)
        {
            ComObject pCadRegion = null;

            try
            {
                IPointCollection pPts = pRing as IPointCollection;
                int ptCount = pPts.PointCount;
                double[] dblVertex = new double[ptCount * 2];
                for (int j = 0; j < ptCount; j++)
                {
                    dblVertex[j * 2] = pPts.get_Point(j).X;
                    dblVertex[j * 2 + 1] = pPts.get_Point(j).Y;

                }
                ComObject pModelSpace = ComObject.CreateInstance(mCadDoc2["ModelSpace"]);
                //IAcadLWPolyline pCadPolyline = mCadDoc.ModelSpace.AddLightWeightPolyline(dblVertex);
                object objPolyline = pModelSpace.InvokeMethod("AddLightWeightPolyline", dblVertex);
                ComObject pCadPolyline = ComObject.CreateInstance(objPolyline);
                // pCadPolyline.Closed = true;
                pCadPolyline["Closed"] = true;

                //IAcadLWPolyline[] pEnts = new IAcadLWPolyline[] { pCadPolyline };
                object[] pEnts = new object[1];
                pEnts[0] = objPolyline;
                //object obj = mCadDoc.ModelSpace.AddRegion(pEnts) as object;

                object obj = ComObject.CreateInstance(pModelSpace.InvokeMethod("AddRegion", pEnts));



                //if (obj is IAcadRegion) pCadRegion = obj as AcadRegion;
                //else if (obj is object[])
                //{
                //    object[] objs = obj as object[];
                //    if (objs.Length > 0)
                //    {
                //        object obj2 = objs[0];
                //        if (obj2 is IAcadRegion) pCadRegion = obj2 as AcadRegion;
                //    }
                //}
                // pCadPolyline.Delete();    

                if (obj is ComObject[])
                {
                    ComObject[] objs = obj as ComObject[];
                    if (objs.Length > 0)
                    {
                        ComObject obj2 = objs[0];
                        pCadRegion = obj2 as ComObject;
                    }
                }
                pCadPolyline.InvokeMethod("Delete");
            }
            catch (System.Exception)
            {
            }
            return pCadRegion;
        }

        private AcadRegion EsriRing2CadRegion(IRing pRing, string strLayerName, AcadAcCmColor pCadColor)
        {
            AcadRegion pCadRegion = null;

            try
            {
                IPointCollection pPts = pRing as IPointCollection;
                int ptCount = pPts.PointCount;
                double[] dblVertex = new double[ptCount * 2];
                for (int j = 0; j < ptCount; j++)
                {
                    dblVertex[j * 2] = pPts.get_Point(j).X;
                    dblVertex[j * 2 + 1] = pPts.get_Point(j).Y;

                }
                IAcadLWPolyline pCadPolyline = mCadDoc.ModelSpace.AddLightWeightPolyline(dblVertex);
                pCadPolyline.Closed = true;
                IAcadLWPolyline[] pEnts = new IAcadLWPolyline[] { pCadPolyline };

                object obj = mCadDoc.ModelSpace.AddRegion(pEnts) as object;
                if (obj is IAcadRegion) pCadRegion = obj as AcadRegion;
                else if (obj is object[])
                {
                    object[] objs = obj as object[];
                    if (objs.Length > 0)
                    {
                        object obj2 = objs[0];
                        if (obj2 is IAcadRegion)
                        {
                            pCadRegion = obj2 as AcadRegion;
                            pCadRegion.Layer = strLayerName;
                        }
                    }
                }
                pCadPolyline.Delete();
                Marshal.ReleaseComObject(pCadPolyline);
            }
            catch (System.Exception)
            {
            }
            return pCadRegion;
        }

        private Region EsriRing2CadRegion(Transaction pTran,BlockTableRecord pBtr, IRing pRing, string strLayerName, DWGdirect.Colors.Color pCadColor)
        {            
            Region pCadRegion = null;
            try
            {
                DWGdirect.DatabaseServices.Polyline pCadPolyline = new DWGdirect.DatabaseServices.Polyline();
                IPointCollection pPts = pRing as IPointCollection;
                int ptCount = pPts.PointCount;              
                for (int j = 0; j < ptCount; j++)
                {
                    pCadPolyline.AddVertexAt(pCadPolyline.NumberOfVertices, new Point2d(pPts.get_Point(j).X, pPts.get_Point(j).Y), 0, 0, 0);
                }             
                pCadPolyline.Closed = true;
              
                pCadPolyline.SetDatabaseDefaults(pBtr.Database);

                DBObjectCollection pDbjs = new DBObjectCollection();
                pDbjs.Add(pCadPolyline);            
                DBObjectCollection objs=   Region.CreateFromCurves(pDbjs);
                if (objs.Count > 0)
                {
                    object obj2 = objs[0];
                    if (obj2 is Region)
                    {
                       
                        pCadRegion = obj2 as Region;

                        pBtr.AppendEntity(pCadRegion);
                        pTran.AddNewlyCreatedDBObject(pCadRegion, true);
                        pCadRegion.Layer = strLayerName;
                        pCadRegion.Color = pCadColor;
                    }
                }               
                     
            }
            catch (System.Exception)
            {
            }
            return pCadRegion;
        }
        private Region EsriRing2CadRegion(Transaction pTran, BlockTableRecord pBtr, IPointCollection pPts, string strLayerName, DWGdirect.Colors.Color pCadColor)
        {
            Region pCadRegion = null;
            try
            {
                DWGdirect.DatabaseServices.Polyline pCadPolyline = new DWGdirect.DatabaseServices.Polyline();
               // IPointCollection pPts = pRing as IPointCollection;
                int ptCount = pPts.PointCount;
                for (int j = 0; j < ptCount; j++)
                {
                    pCadPolyline.AddVertexAt(pCadPolyline.NumberOfVertices, new Point2d(pPts.get_Point(j).X, pPts.get_Point(j).Y), 0, 0, 0);
                }
                pCadPolyline.Closed = true;

                pCadPolyline.SetDatabaseDefaults(pBtr.Database);

                DBObjectCollection pDbjs = new DBObjectCollection();
                pDbjs.Add(pCadPolyline);
                DBObjectCollection objs = Region.CreateFromCurves(pDbjs);
                if (objs.Count > 0)
                {
                    object obj2 = objs[0];
                    if (obj2 is Region)
                    {

                        pCadRegion = obj2 as Region;

                        pBtr.AppendEntity(pCadRegion);
                        pTran.AddNewlyCreatedDBObject(pCadRegion, true);
                        pCadRegion.Layer = strLayerName;
                        pCadRegion.Color = pCadColor;
                    }
                }

            }
            catch (System.Exception ex)
            {
                LogHelper.WriteLog(ex);
            }
            return pCadRegion;
        }

        /// <summary>
        /// ArcEngiene Annotation to AutoCAD Single Line Text
        /// </summary>
        /// <param name="pPolyline"></param>
        /// <returns></returns>
        public IAcadText Esri2CadText(ITextElement pEsriTxt, string strLayerName, double dblScale)
        {
            IAcadText pAcadTxt = null;
            try
            {
                ITextSymbol pEsriTxtSym = pEsriTxt.Symbol;
                IElement pElement = pEsriTxt as IElement;
                IEnvelope pEnv = pElement.Geometry.Envelope;

                double[] dblPosition = new double[] { (pEnv.XMax + pEnv.XMin) * 0.5, (pEnv.YMax + pEnv.YMin) * 0.5, 0 };
                pAcadTxt = mCadDoc.ModelSpace.AddText(pEsriTxt.Text, dblPosition, (double)pEsriTxtSym.Font.Size / 3000 * dblScale);
                pAcadTxt.Rotation = pEsriTxt.Symbol.Angle*Math.PI /180;
                // pAcadTxt.Alignment = AcAlignment.acAlignmentMiddleCenter;
                pAcadTxt.Layer = strLayerName;
            }
            catch (System.Exception)
            {
            }
            return pAcadTxt;
        }
        public DBText Esri2CadText(Transaction pTran,BlockTableRecord pBtr, ITextElement pEsriTxt, string strLayerName, double dblScale)
        {
            DBText txt=null;
            try
            {
                ITextSymbol pEsriTxtSym = pEsriTxt.Symbol;
                IElement pElement = pEsriTxt as IElement;
                IEnvelope pEnv = pElement.Geometry.Envelope;

                double[] dblPosition = new double[] { (pEnv.XMax + pEnv.XMin) * 0.5, (pEnv.YMax + pEnv.YMin) * 0.5, 0 };

                txt= new DBText();
                txt.Layer = strLayerName;
                txt.Position = new Point3d(dblPosition);
                txt.TextString = pEsriTxt.Text;
                txt.Height = (double)pEsriTxtSym.Font.Size / 3000 * dblScale;

                pBtr.AppendEntity(txt);
                pTran.AddNewlyCreatedDBObject(txt, true);
            }
            catch (System.Exception)
            {
               
            }
            return txt ;
        }

        /// <summary>
        /// ArcEngiene Point to AutoCAD Blockreference
        /// </summary>
        /// <param name="pPolyline"></param>
        /// <returns></returns>
        public IAcadBlockReference EsriPt2CadBlock(IPoint pEsriPt, string strBlockFile, double dblAngle, string strLayerName)
        {
            IAcadBlockReference pBr = null;
            try
            {
                if (System.IO.File.Exists(strBlockFile) == false) return null;
                //pAcadBlock = mCadDoc.Blocks.Add(new double[] { pEsriPt.X, pEsriPt.Y, 0 }, strBlockFile);
                pBr = mCadDoc.ModelSpace.InsertBlock(new double[] { pEsriPt.X, pEsriPt.Y, 0 }, strBlockFile, 0.5, 0.5, 0.5, dblAngle/180*Math.PI , "");
                pBr.Layer = strLayerName;
            }
            catch (System.Exception ex)
            {
                LogHelper.WriteLog(ex);
            }
            return pBr;
        }
        public BlockReference  EsriPt2CadBlock(Database pDb, Transaction pTran, BlockTable pBt, BlockTableRecord pBtr, IPoint pEsriPt, string strBlockFile, double dblAngle, string strLayerName)
        {
            BlockReference br = null; ;
            try
            {
                if (System.IO.File.Exists(strBlockFile) == false) return br ;
                string blockName = System.IO.Path.GetFileNameWithoutExtension(strBlockFile);
                if (pBt.Has(blockName) == false)
                {
                    Database objSrcDb = new Database(false, true);
                    Transaction objSrcTran = objSrcDb.TransactionManager.StartTransaction();
                    objSrcDb.ReadDwgFile(strBlockFile, System.IO.FileShare.Read, true, "");
                    pDb.Insert(blockName, objSrcDb, false);
                    objSrcTran.Commit();
                    objSrcTran.Dispose();
                    objSrcDb.Dispose();
                }
               br = new BlockReference(new Point3d(pEsriPt.X, pEsriPt.Y, 0), pBt[blockName]);
                br.Rotation = dblAngle / 180 * Math.PI;

                br.ScaleFactors = new Scale3d(0.5, 0.5, 0.5);
                pBtr.AppendEntity(br);
                pTran.AddNewlyCreatedDBObject(br, true);
                br.Layer = strLayerName;
            }
            catch
            {
               
            }
            return br ;          
        }

        public IAcadPoint Esri2CadPt(IPoint pEsriPt, string strLayerName)
        {
            IAcadPoint pCadPt = null;
            try
            {
                pCadPt = mCadDoc.ModelSpace.AddPoint(new double[] { pEsriPt.X, pEsriPt.Y, 0 });
                pCadPt.Layer = strLayerName;
            }
            catch (System.Exception)
            {
            }
            return pCadPt;
        }
        public DBPoint  Esri2CadPt(Transaction pTran,BlockTableRecord pBtr,IPoint pEsriPt, string strLayerName)
        {
            DBPoint pt=null ;
            try
            {
                 pt = new DBPoint(new Point3d(pEsriPt.X, pEsriPt.Y, 0));
                pBtr.AppendEntity(pt);
                pTran.AddNewlyCreatedDBObject(pt, true);
            }
            catch (System.Exception)
            {
               
            }
            return pt;          
        }

        public bool  CreateCadLayer(string strLayerName)
        {
            //AcadLayer pCadLayer = null;
            //try
            //{
            //    pCadLayer = mCadDoc.Layers.Add(strLayerName);
            //}
            //catch (System.Exception)
            //{
            //}

            //return pCadLayer;
            try
            {
                LayerTable lt = mDb.LayerTableId.GetObject(OpenMode.ForWrite) as LayerTable;
                if (lt.Has(strLayerName) == false)
                {
                    LayerTableRecord ltr = new LayerTableRecord();
                    ltr.Name = strLayerName;
                    lt.Add(ltr);
                }
            }
            catch
            {
                return false;
            }
            return true;
           
        }
        public ComObject CreateCadLayer2(string strLayerName)
        {
            ComObject pCadLayers = ComObject.CreateInstance(mCadDoc2["Layers"]);
            //AcadLayer pCadLayer = mCadDoc.Layers.Add(strLayerName);
            ComObject pCadLayer = ComObject.CreateInstance(pCadLayers.InvokeMethod("Add", strLayerName));
            return pCadLayer;
        }
    }
}



 